package com.jtech.together.view.fragment;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.bilibili.magicasakura.widgets.TintImageView;
import com.jtech.together.R;
import com.jtech.together.manager.UserManager;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.MyProfileContract;
import com.jtech.together.mvp.presenter.MyProfilePresenter;
import com.jtech.together.util.ActivityJump;
import com.jtech.together.util.ImageSelect;
import com.jtech.together.util.ImageUtils;
import com.jtech.together.util.SexUtil;
import com.jtech.together.util.ThemeHelper;
import com.jtech.together.util.Util;
import com.jtech.together.view.activity.LoginActivity;
import com.jtech.together.view.activity.MainActivity;
import com.jtech.together.view.activity.ModifyBioActivity;
import com.jtech.together.view.activity.ModifyNicknameActivity;
import com.jtech.together.view.activity.SettingActivity;
import com.jtech.together.view.fragment.base.BaseFragment;
import com.jtech.together.view.weight.dialog.BirthdayDialog;
import com.jtech.together.view.weight.dialog.CardPickerDialog;
import com.jtech.together.view.weight.dialog.CustomProgressDialog;
import com.jtech.together.view.weight.dialog.SexDialog;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 我的信息
 * Created by wuxubaiyang on 2017/5/10.
 */
public class MyProfileFragment extends BaseFragment implements MyProfileContract.View, Toolbar.OnMenuItemClickListener {
    private static final int REQUEST_MODIFY = 0x5411;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.imagebutton_myprofile_avatar)
    ImageButton imageButtonAvatar;
    @Bind(R.id.textview_myprofile_nickname)
    TextView textViewNickname;
    @Bind(R.id.textview_myprofile_sex)
    TextView textViewSex;
    @Bind(R.id.textview_myprofile_birthday)
    TextView textViewBirthday;
    @Bind(R.id.textview_myprofile_bio)
    TextView textViewBio;
    @Bind(R.id.content)
    CoordinatorLayout content;
    @Bind(R.id.imageview_myprofile_theme)
    TintImageView tintImageViewTheme;

    private MyProfileContract.Presenter presenter;

    @Override
    public View createView(LayoutInflater layoutInflater, ViewGroup viewGroup) {
        return layoutInflater.inflate(R.layout.fragment_myprofile, viewGroup, false);
    }

    @Override
    protected void initVariables(Bundle bundle) {
        //绑定P类
        presenter = new MyProfilePresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        //设置是否显示menu
        setHasOptionsMenu(true);
        //设置标题栏
        ((MainActivity) getActivity()).setSupportActionBar(toolbar);
        //设置标题栏菜单点击事件
        toolbar.setOnMenuItemClickListener(this);
    }

    @Override
    protected void loadData() {
        //设置我的信息
        setMyProfile(presenter.getMyUserProfile());
    }

    public static MyProfileFragment newInstance() {
        Bundle args = new Bundle();
        MyProfileFragment fragment = new MyProfileFragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 设置我的信息
     *
     * @param userModel
     */
    private void setMyProfile(UserModel userModel) {
        //显示用户头像
        ImageUtils.showCircleImage(getActivity(), userModel.getAvatar(), imageButtonAvatar,
                R.drawable.ic_default_avatar, R.drawable.ic_default_avatar);
        //设置昵称
        textViewNickname.setText(userModel.getNickname());
        //设置性别
        textViewSex.setText(SexUtil.getSex(userModel.getSex()));
        //设置生日
        long birthday = userModel.getBirthday();
        textViewBirthday.setText(Util.formatBirthday(birthday) + "\t(" + Util.getAge(birthday) + "岁)");
        //设置简介
        textViewBio.setText(userModel.getBio());
    }

    /**
     * 主题色选择
     *
     * @param currentTheme
     */
    private void setSelectTheme(int currentTheme) {
        if (ThemeHelper.getTheme(getActivity()) != currentTheme) {
            ThemeHelper.setTheme(getActivity(), currentTheme);
            ThemeUtils.refreshUI(getActivity(), new ThemeUtils.ExtraRefreshable() {
                        @Override
                        public void refreshGlobal(Activity activity) {
                            //for global setting, just do once
                            if (Build.VERSION.SDK_INT >= 21) {
                                ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(null, null,
                                        ThemeUtils.getThemeAttrColor(getActivity(), android.R.attr.colorPrimary));
                                getActivity().setTaskDescription(taskDescription);
                                getActivity().getWindow().setStatusBarColor(
                                        ThemeUtils.getColorById(getActivity(), R.color.theme_color_primary));
                            }
                        }

                        @Override
                        public void refreshSpecificView(View view) {
                        }
                    }
            );
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        //实例化菜单
        inflater.inflate(R.menu.menu_my_profile, menu);
    }

    @Override
    public void updateAvatarSuccess(String avatarPath, String avatarUrl) {
        CustomProgressDialog.dismissProgressDialog();
        //显示头像，path为本地图片路径，url为网络地址
        ImageUtils.showCircleImage(getActivity(), avatarPath, imageButtonAvatar,
                R.drawable.ic_default_avatar, R.drawable.ic_default_avatar);
    }

    @Override
    public void updateSexSuccess(int sex) {
        CustomProgressDialog.dismissProgressDialog();
        textViewSex.setText(SexUtil.getSex(sex));
    }

    @Override
    public void updateBirthdaySuccess(long birthday) {
        CustomProgressDialog.dismissProgressDialog();
        textViewBirthday.setText(Util.formatBirthday(birthday) + "\t(" + Util.getAge(birthday) + "岁)");
    }

    @Override
    public void updateFail(String error) {
        CustomProgressDialog.dismissProgressDialog();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    /**
     * 综合点击事件
     *
     * @param v
     */
    @OnClick({R.id.imagebutton_myprofile_avatar, R.id.textview_myprofile_nickname, R.id.textview_myprofile_sex,
            R.id.textview_myprofile_birthday, R.id.textview_myprofile_bio, R.id.textview_myprofile_theme})
    public void onOnClick(View v) {
        Intent intent;
        Bundle bundle;
        switch (v.getId()) {
            case R.id.imagebutton_myprofile_avatar://头像点击事件
                ImageSelect.singleSelect(MyProfileFragment.this, true);
                break;
            case R.id.textview_myprofile_nickname://昵称点击事件
                intent = new Intent(getActivity(), ModifyNicknameActivity.class);
                bundle = new Bundle();
                bundle.putString(ModifyNicknameActivity.KEY_DEFAULT_NICKNAME,
                        textViewNickname.getText().toString());
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_MODIFY);
                break;
            case R.id.textview_myprofile_sex://性别点击事件
                SexDialog.build(getActivity())
                        .setOnClickListener(new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                presenter.updateSex(which);
                                CustomProgressDialog.showProgressDialog(getActivity(), "正在更新性别");
                            }
                        }).show();
                break;
            case R.id.textview_myprofile_birthday://生日点击事件
                BirthdayDialog.build(getActivity())
                        .setDefaultTime(presenter.getMyUserProfile().getBirthday())
                        .setBirthdaySelectDoneListener(new BirthdayDialog.OnBirthdaySelectDoneListener() {
                            @Override
                            public void onSelectDone(long birthday, int year, int month, int dayOfMonth) {
                                if (Util.isBornFuture(birthday)) {
                                    Snackbar.make(toolbar, "您老要在未来诞生么~", Snackbar.LENGTH_SHORT).show();
                                    return;
                                }
                                CustomProgressDialog.showProgressDialog(getActivity(), "正在更新生日");
                                presenter.updateBirthday(birthday);
                            }
                        }).show();
                break;
            case R.id.textview_myprofile_bio://个人简介点击事件
                intent = new Intent(getActivity(), ModifyBioActivity.class);
                bundle = new Bundle();
                bundle.putString(ModifyBioActivity.KEY_DEFAULT_BIO,
                        textViewBio.getText().toString());
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_MODIFY);
                break;
            case R.id.textview_myprofile_theme://主题选择
                new CardPickerDialog()
                        .setClickListener(new CardPickerDialog.ClickListener() {
                            @Override
                            public void onConfirm(int currentTheme) {
                                setSelectTheme(currentTheme);
                            }
                        }).show(getChildFragmentManager(), CardPickerDialog.TAG);
                break;
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.setting://跳转到设置页面
                startActivityForResult(new Intent(getActivity(), SettingActivity.class), 0);
                return true;
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断是否为图片选择返回
        if (ImageSelect.isRequestImageResult(requestCode, resultCode)) {
            List<String> imageList = ImageSelect.getRequestImage(data);
            if (null != imageList && imageList.size() > 0) {
                //上传用户头像
                presenter.updateAvatar(imageList.get(0));
                CustomProgressDialog.showProgressDialog(getActivity(), "正在更新头像");
            }
        }
        //判断是否已注销
        if (!UserManager.isLogin()) {
            //注销之后跳转到登录页面
            ActivityJump.build(getActivity(), LoginActivity.class)
                    .jump();
            //退出主页
            getActivity().onBackPressed();
        }
        //判断是否是从编辑页面跳转回来的
        if (resultCode == MainActivity.RESULT_OK && requestCode == REQUEST_MODIFY) {
            setMyProfile(presenter.getMyUserProfile());
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
    }
}